package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.widget.BookCoverView;
import com.shwread.android.ui.widget.xlistview.XListView;
import com.shwread.android.ui.widget.xlistview.XListView.IXListViewListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryEnterpriseJournalListAction;
import com.shwread.httpsdk.http.face.QryEnterpriseZoneBookMoreAction;
import com.tgx.tina.android.task.ATaskService;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import logic.bean.BookInfo;
import logic.bean.ColumDetailNew;
import logic.bean.ColumnDetail;
import logic.bean.JournalColumn;
import logic.bean.JournalInfo;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.Util;

/**
 * 书籍列表页面
 *
 * @author 刘宾
 * @date 2014年8月25日 上午10:26:42
 */
public class ColumnDetailActivity  extends  BaseBusinessActivity  implements  OnClickListener,  IXListViewListener {
    private int pageNum = 1;
    private TextView tvTitle;
    private Button btnBack;
    private XListView lv;
    private LinearLayout llEmpty;
    private JournalInfo journalInfo;
    private List<JournalColumn> columns;
    private ColumDetailNew columnDetail;
    private List<BookInfo> allData;
    /**
     * 是否从企业内刊过来
     */
    private boolean isJournal = false;
    private Bundle b;
    private String columnName, blockTypeName;
    private int mark;
    private int columnId, blockTypeId;
    private int firstSortId, secondSortId;
    private long blockId;
    private Adapter adapter;

    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;

    /**
     * 1:从精品页面过来,2:从员工必读 过来,3:从企业内刊过来
     */
    private int source;

    private boolean hasMore = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        allData = new ArrayList<BookInfo>();
        columns = new ArrayList<JournalColumn>();

        mAService = new ATaskService();
        mAService.startAService(this);

        findViews();
        updateLoadingView(0);

        final Intent intent = getIntent();
        //从精品页面过来
        if (intent.hasExtra("bundle")) {
            b = getIntent().getBundleExtra("bundle");
            columnId = b.getInt("columnId");
            columnName = b.getString("columnName");
            firstSortId = b.getInt("firstSortId");
            secondSortId = b.getInt("secondSortId");
            mark = b.getInt("mark");
            tvTitle.setText(columnName);
            if (mark == 1) {
                source = 1;
            } else {
                source = 4;
            }
            //			new QryBooksByColumnIdAction(this, columnId, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksAction()).start();
            //从员工必读 过来
        } else if (intent.hasExtra("blockId") && intent.hasExtra("blockTypeId") && intent.hasExtra("blockTypeName")) {
            blockId = intent.getIntExtra("blockId", 0);
            blockTypeId = intent.getIntExtra("blockTypeId", 0);
            blockTypeName = intent.getStringExtra("blockTypeName");
            tvTitle.setText(blockTypeName);
            source = 2;
            //			new QryEnterpriseZoneBookMoreAction(this, String.valueOf(blockTypeId), String.valueOf(blockId), "", pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksAction()).start();
            //从企业内刊过来
        } else if (intent.hasExtra("journal")) {
            isJournal = true;
            tvTitle.setText(getResources().getString(R.string.enterprise_journal));
            source = 3;
            //			new QryEnterpriseJournalListAction(this, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksAction()).start();
        } else {
            Util.showToast(this, "缺少参数");
            finish();
            return;
        }
        getData(false);
    }

    private void getData(boolean isRefresh) {
        if (!NetworkUtil.isConnected(this)) {
            Util.showToast(this, "请检查网络连接");
            onFinish();
            return;
        }
        //1:从精品页面过来,2:从员工必读 过来,3:从企业内刊过来,4:从精品页面分类过来
        switch (source) {
            case 1:
                //				new QryBooksByColumnIdAction(this, columnId, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksAction(isRefresh)).start();
                NewActionHelp.qryBooksByColumnId(this, columnId, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksColumnDetailHandler(isRefresh));
                break;
            case 2:
                new QryEnterpriseZoneBookMoreAction(this, String.valueOf(blockTypeId), String.valueOf(blockId), "", pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksAction(isRefresh)).start();
                break;
            case 3:
                new QryEnterpriseJournalListAction(this, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBooksAction(isRefresh)).start();
                break;
            case 4:
                NewActionHelp.qryBookListBySort(this, firstSortId, secondSortId, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetBookListBySortHandler(isRefresh));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAService != null) {
            mAService.stopAService();
        }
    }

    private class GetBookListBySortHandler
            extends
            ObjectHttpResponseHandler<ColumDetailNew> {

        boolean isRefresh;

        public GetBookListBySortHandler(boolean isRef) {
            isRefresh = isRef;
        }

        @Override
        public Type getType() {
            return new TypeToken<ColumDetailNew>() {
            }.getType();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            getUIHandler().sendEmptyMessage(-1);

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, final ColumDetailNew obj, String responseString) {
            if (null == obj || obj.getBookInfos() == null || obj.getBookInfos().size() == 0) {
                hasMore = false;
                getUIHandler().sendEmptyMessage(0);
                return;
            }
            if (obj != null && obj instanceof ColumDetailNew) {
                columnDetail = obj;
                if (columnDetail.getBookInfos() != null) {
                    if (columnDetail.getPage() < columnDetail.getTotalPage()) {
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }
                    if (isRefresh) {
                        allData.clear();
                        lastRefreshTime = System.currentTimeMillis();
                    }
                    allData.addAll(columnDetail.getBookInfos());
                    getUIHandler().sendEmptyMessage(1);
                }
                if (null == columnDetail || columnDetail.getBookInfos() == null || columnDetail.getBookInfos().size() < DefaultConsts.DEFAULT_PAGE_LENGTH) {
                    if (!isRefresh) getUIHandler().sendEmptyMessage(2);
                }
            }
        }

    }

    private class GetBooksColumnDetailHandler
            extends
            ObjectHttpResponseHandler<ColumDetailNew> {
        boolean isRefresh;

        public GetBooksColumnDetailHandler(boolean isRef) {
            isRefresh = isRef;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            getUIHandler().sendEmptyMessage(-1);

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, final ColumDetailNew obj, String responseString) {
            if (null == obj || obj.getBookInfos() == null || obj.getBookInfos().size() == 0) {
                hasMore = false;
                getUIHandler().sendEmptyMessage(0);
                return;
            }
            if (obj != null && obj instanceof ColumDetailNew) {
                columnDetail = obj;
                if (columnDetail.getBookInfos() != null) {
                    if (columnDetail.getPage() < columnDetail.getTotalPage()) {
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }
                    if (isRefresh) {
                        allData.clear();
                        lastRefreshTime = System.currentTimeMillis();
                    }
                    allData.addAll(columnDetail.getBookInfos());
                    getUIHandler().sendEmptyMessage(1);
                }
                if (null == columnDetail || columnDetail.getBookInfos() == null || columnDetail.getBookInfos().size() < DefaultConsts.DEFAULT_PAGE_LENGTH) {
                    if (!isRefresh) getUIHandler().sendEmptyMessage(2);
                }
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<ColumDetailNew>() {
            }.getType();
        }

    }

    private class GetBooksAction
            extends
            BaseAction {
        boolean isRefresh;

        public GetBooksAction(boolean isRef) {
            isRefresh = isRef;
        }

        @Override
        public void OK(Object obj) {
            if (obj instanceof ColumnDetail) {
                if (null == obj || ((ColumnDetail) obj).getBookInfos() == null || ((ColumnDetail) obj).getBookInfos().size() == 0) {
                    hasMore = false;
                    getUIHandler().sendEmptyMessage(0);
                    return;
                }
            }
            if (obj instanceof JournalInfo) {
                if (null == obj || ((JournalInfo) obj).getColumns() == null || ((JournalInfo) obj).getColumns().size() == 0) {
                    hasMore = false;
                    getUIHandler().sendEmptyMessage(0);
                    return;
                }
            }
            if (obj != null && obj instanceof ColumnDetail) {
                columnDetail = (ColumDetailNew) obj;
                if (columnDetail.getBookInfos() != null) {
                    if (columnDetail.getPage() < columnDetail.getTotalPage()) {
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }
                    if (isRefresh) {
                        allData.clear();
                        lastRefreshTime = System.currentTimeMillis();
                    }
                    allData.addAll(columnDetail.getBookInfos());
                    getUIHandler().sendEmptyMessage(1);
                }
                if (null == columnDetail || columnDetail.getBookInfos() == null || columnDetail.getBookInfos().size() < DefaultConsts.DEFAULT_PAGE_LENGTH) {
                    if (!isRefresh) getUIHandler().sendEmptyMessage(2);
                }
            } else if (obj != null && obj instanceof JournalInfo) {
                journalInfo = (JournalInfo) obj;
                if (journalInfo.getColumns() != null) {
                    if (journalInfo.getPage() < journalInfo.getTotalPage()) {
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }
                    if (isRefresh) {
                        columns.clear();
                        lastRefreshTime = System.currentTimeMillis();
                    }
                    columns.addAll(journalInfo.getColumns());
                    getUIHandler().sendEmptyMessage(1);
                }
                if (null == journalInfo || journalInfo.getColumns() == null || journalInfo.getColumns().size() < DefaultConsts.DEFAULT_PAGE_LENGTH) {
                    if (!isRefresh) getUIHandler().sendEmptyMessage(2);
                }
            }
        }

        @Override
        protected void onError() {
            super.onError();
            getUIHandler().sendEmptyMessage(-1);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    lv.setVisibility(View.GONE);
                    llEmpty.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    lv.setRefreshTime(new SimpleDateFormat("MM-dd HH:mm:ss", Locale.CHINA).format(new Date(lastRefreshTime)));
                    onFinish();
                    updateLoadingView(1);
                    adapter.notifyDataSetChanged();
                    break;
                case 2:
                    lv.setPullLoadEnable(false);
                    onFinish();
                    break;
                case -1:
                    updateLoadingView(-1);
                    onFinish();
                    break;
            }
        }

        ;
    };

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    private void findViews() {
        setContentView(R.layout.column_detail);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        btnBack = (Button) findViewById(R.id.common_header_back);
        loadingView = findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);
        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        lv = (XListView) findViewById(R.id.column_detail_listview);
        llEmpty = (LinearLayout) findViewById(R.id.ll_book_column_detail_empty);
        llEmpty.setVisibility(View.GONE);
        adapter = new Adapter();
        lv.setRefreshTime("刚刚");
        lv.setPullLoadEnable(true);
        //		lv.hideLoadMore();
        lv.setXListViewListener(this);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Object obj = arg0.getAdapter().getItem(arg2);
                final BookInfo info = isJournal ? BookInfo.toBookInfo((JournalColumn) obj) : (BookInfo) obj;
                //TODO 缺少书籍类型对应的处理
                //info.CloudBook_Type
                //#ifdef SHOW_OLDBOOKDETAIL
                //$ Intent intent = new Intent(ColumnDetailActivity.this, BookDetailActivity.class);
                //#else
                Intent intent = new Intent(ColumnDetailActivity.this, NewBookDetailActivity.class);
                //#endif
                intent.putExtra("BookInfo", info);
                startActivity(intent);
            }
        });
        lv.setAdapter(adapter);
    }

    private class Adapter
            extends
            BaseAdapter {
        private ViewHolder holder;

        @Override
        public int getCount() {
            return isJournal ? columns.size() : allData.size();
        }

        @Override
        public Object getItem(int position) {
            return isJournal ? columns.get(position) : allData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            Object obj = getItem(position);
            BookInfo b = isJournal ? BookInfo.toBookInfo((JournalColumn) obj) : (BookInfo) obj;

            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(ColumnDetailActivity.this).inflate(R.layout.common_book_item, null);
                holder.name = (TextView) view.findViewById(R.id.common_book_item_name);
                holder.author = (TextView) view.findViewById(R.id.common_book_item_author);
                holder.intro = (TextView) view.findViewById(R.id.common_book_item_intro);
                holder.cover = (BookCoverView) view.findViewById(R.id.common_book_item_cover);
                //				holder.cover = (SmartImageView) view.findViewById(R.id.common_book_item_cover);
                holder.typeImg = (ImageView) view.findViewById(R.id.common_book_item_type_img);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.cover.setImageUrl(b.getLogoUrl(), b.getCoverTagPicUrl());
            //			holder.cover.setImageUrl(b.getLogoUrl());
            holder.name.setText(b.getName());
            holder.author.setText("作者：" + b.getAuthor());
            holder.intro.setText(b.getShortIntro());
            setBookTypeIcon(holder.typeImg, b.getContent_type());
            return view;
        }

    }

    private class ViewHolder {
        TextView name, author, intro;
        ImageView typeImg;
        BookCoverView cover;
        //		SmartImageView  cover;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    private long lastRefreshTime = System.currentTimeMillis();

    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                lv.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                lv.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                lv.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        if (hasMore) lv.setPullLoadEnable(true);
        getData(true);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        getData(false);
    }

    private void onFinish() {
        lv.stopRefresh();
        lv.stopLoadMore();
    }
}
